<template>
  <div class="content">
    <van-form validate-first @submit="onSubmit" @failed="onFailed">
      <div
        style="
          color: red;
          line-height: 30px;
          font-size: 12px;
          margin-left: -80px;
        "
      >
        请上传学员身份证正面，上传完毕学员信息将自动填充
      </div>
      <van-field name="uploader" label="身份证">
        <template #input>
          <van-uploader
            v-model="idcardFileList"
            @delete="deleteImgIdcard"
            :after-read="afterReadIdcard"
            :max-count="1"
          />
        </template>
      </van-field>
      <div
        class="input-idCard"
        style="
          position: relative;
          display: flex;
          justify-content: start;
          align-items: center;
        "
      >
        <div
          class="label-idCard"
          @click="showIdTypePicker = true"
          style="font-size: 12px; margin-left: 10px"
        >
          {{ form.docType === "1" ? "大陆身份证" : "港澳身份证" }}
          <van-icon name="arrow-down" />
          <span class="icon">*</span>
        </div>
        <van-popup v-model="showIdTypePicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="docType"
            @confirm="onDocTypeConfirm"
            @cancel="showIdTypePicker = false"
          />
        </van-popup>
        <div style="margin-left: 10px">
          <van-field
            class="no-label"
            v-model="form.customerIdentityCard"
            name="customerName"
            placeholder="请输入学员身份证"
            :rules="[{ required: true, message: '请填写学员身份证' }]"
          />
        </div>
      </div>

      <van-field
        v-model="form.customerName"
        name="customerName"
        label="学员姓名"
        placeholder="请输入学员姓名"
        :rules="[{ required: true, message: '请填写用户名' }]"
        class="required"
      />
      <van-field
        v-model="form.customerPhone"
        name="customerPhone"
        label="学员电话"
        placeholder="请输入学员电话"
        :rules="[{ required: true, message: '请输入学员电话' }]"
        class="required"
        @change="getUserInfoByPhone"
      />
      <van-field
        readonly
        clickable
        name="schoolId"
        :value="schoolName"
        label="校 区"
        placeholder="点击选择校区"
        @click="showPicker = true"
        :rules="[{ required: true, message: '请选择校区' }]"
        class="required"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="schoolList"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
      <van-field
        readonly
        clickable
        name="goodsId"
        :value="goodsName"
        label="商 品"
        :placeholder="!form.schoolId ? '请先选择校区' : '点击选择商品'"
        @click="showGoodsPicker = true"
        :disabled="!form.schoolId"
        @change="handleGoaods"
        :rules="[{ required: true, message: '请选择商品' }]"
        class="required"
      />
      <van-popup v-model="showGoodsPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="goodsList"
          @confirm="onGoodsConfirm"
          @cancel="showGoodsPicker = false"
        />
      </van-popup>
      <van-field
        v-model="form.goodsPrice"
        name="goodsPrice"
        label="商品金额"
        placeholder="请输入商品金额"
        :rules="[{ required: true, message: '请填写商品金额' }]"
        :disabled="true"
        class="required"
      />
      <van-field
        v-model="form.orderPrice"
        name="orderPrice"
        label="订单金额"
        placeholder="请输入订单金额"
        :rules="[{ required: true, message: '请填写订单金额' }]"
        :disabled="true"
        class="required"
      />
      <van-field
        v-model="form.actualAmount"
        name="actualAmount"
        label="实付金额"
        placeholder="请输入实付金额"
        :rules="[{ required: true, message: '请填写实付金额' }]"
        :disabled="true"
        class="required"
      />
      <van-field
        v-model="form.remark"
        name="remark"
        label="备注"
        placeholder="请输入备注"
      />
      <van-field
        v-model="form.customerService"
        name="customerService"
        label="业务员"
        placeholder="请输入业务员"
      />
      <van-field
        v-model="form.customerServicePhone"
        name="customerServicePhone"
        label="业务员电话"
        placeholder="请输入业务员电话"
      />
      <van-field
        v-if="isShow"
        readonly
        clickable
        name="carModel"
        :value="carModelName"
        label="车 型"
        :placeholder="!form.goodsId ? '请先选择商品' : '点击选择车型'"
        @click="showCarmodelPicker = true"
        :disabled="!form.goodsId"
        class="required"
      />
      <van-popup v-model="showCarmodelPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="carModel"
          @confirm="onCarmodelConfirm"
          @cancel="showCarmodelPicker = false"
        />
      </van-popup>
      <div class="upload-pay">
        <van-field name="uploader" label="支付凭证" class="required">
          <template #input>
            <van-uploader
              v-model="uploader"
              @delete="deleteImg"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <div
          style="
            color: red;
            line-height: 30px;
            font-size: 12px;
            margin-left: -200px;
          "
        >
          请上传学员支付凭证、支付截图
        </div>
      </div>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from "vue";
import { Toast } from "vant";

Vue.use(Toast);
import Upload from "@/components/Upload";
// import Upload from "@/components/Upload.vue";
import {
  getSchoolList,
  getGoodsList,
  createOrder,
  uploadFile,
  idCard,
  getUserInfo,
} from "@/api/index";
export default {
  components: {
    Upload,
  },
  data() {
    return {
      // 车型
      carModels: [
        {
          value: "1",
          text: "C1",
        },
        {
          value: "2",
          text: "C2",
        },
        {
          value: "3",
          text: "B1",
        },
        {
          value: "4",
          text: "B2",
        },
        {
          value: "5",
          text: "A1",
        },
        {
          value: "6",
          text: "A3",
        },
        {
          value: "7",
          text: "D",
        },
      ],
      form: {
        customerName: "",
        qty: 1,
        payType: 7,
        payStatus: 1,
        goodsId: null,
        carModel: null,
        docType: "1",
      },
      schoolList: [],
      goodsList: [],
      showPicker: false,
      showGoodsPicker: false, //商品弹窗
      showCarmodelPicker: false, //车型弹窗
      showIdTypePicker: false, //身份证类型弹窗
      schoolName: "",
      goodsName: "",
      carModelName: "",
      // 身份证图片
      idcardFileList: [],
      // 已上传的身份证图
      idcardList: [],
      uploader: [],
      // 已上传的图片
      uploaderList: [],
      fileIds: [],
      filePayIds: [],
      goodsDetails: {}, //商品详情
      carModel: [],
      isShow: false, //车型显示隐藏
      docType: [
        {
          text: "大陆身份证",
          value: "1",
        },
        {
          text: "港澳身份证",
          value: "0",
        },
      ],
      validate: false, //校验
    };
  },
  watch: {
    "form.goodsId"(value) {
      this.carModelName = "";
      this.carModel = [];
      this.isShow = false;
      if (this.form.carModel) {
        this.form.carModel = null;
      }
      this.goodsList.forEach((item) => {
        if (item.value === this.form.goodsId) {
          this.goodsDetails = item;
          if (this.goodsDetails) {
            this.goodsDetails.carModelData.forEach((item1) => {
              this.carModels.forEach((item2) => {
                if (item1 === item2.value) {
                  this.carModel.push(item2);
                }
              });
            });
          }
          if (this.carModel.length === 1) {
            this.form.carModel = this.carModel[0].value;
          }
          // console.log("this.form.carModel", this.carModel);
          this.isShow = this.carModel.length > 1 ? true : false;

          // if (this.form.carModel) {
          //   this.form.carModel = null;
          // }
          // if (this.goodsDetails.carModel) {
          //   this.carModel = this.goodsDetails.carModel;
          //   if (this.form.carModel.length === 1) {
          //     this.form.carModel = this.carModel[0].value;
          //   }
          // }
        }
      });
    },
  },
  created() {
    var searchParams = new URLSearchParams(window.location.search);
    var data = searchParams.get("token");
    if (data) {
      localStorage.setItem("token", data);
    }
    // Toast('token',token)
    Toast.fail('fail',data);
    this.fetchSchoolList();
  },
  methods: {
    // 获取个人信息
    getUserInfoByPhone() {
      if (this.form.customerPhone) {
        getUserInfo(this.form.customerPhone).then((res) => {
          if (res.data.code === 200) {
            this.form.customerIdentityCard = res.data.data.customerIdentityCard;
            this.form.customerName = res.data.data.customerName;
            console.log("res", this.form.customerName);
          } else {
            Toast.fail(res.data.msg);
            setTimeout(() => {
              Toast.clear();
            }, 2000);
          }
        });
      }
    },
    // 删除身份证图片
    deleteImgIdcard(file) {
      this.idcardList.map((item, index) => {
        if (item.name === file.file.name) {
          this.idcardList.splice(index, 1);
          // this.filePayIds.splice(index, 1);
          // this.form.fileIds = this.filePayIds;
        }
      });
    },
    // 上传身份证图
    afterReadIdcard(file) {
      Toast.loading({
        duration: 0,
        message: "加载中...",
        forbidClick: true,
      });
      //定义formData
      const formData = new FormData();
      formData.append("files", file.file); // 传入文件
      formData.append("type", 2);
      this.idcardList.push(file.file);
      //调用请求
      uploadFile(formData)
        .then((res) => {
          if (res.data.data) {
            idCard(res.data.data).then((res) => {
              if (res.data.code === 200) {
                this.form.customerIdentityCard = res.data.data.idcard;
                this.form.customerName = res.data.data.name;

                Toast.clear();
              } else {
                Toast.fail(res.data.msg);
                setTimeout(() => {
                  Toast.clear();
                }, 2000);
              }
            });
          }
        })
        .catch((error) => {});
    },
    //  上传支付凭证
    afterRead(file) {
      //定义formData
      const formData = new FormData();
      formData.append("files", file.file); // 传入文件
      formData.append("type", 2);
      this.uploaderList.push(file.file);
      //调用请求
      uploadFile(formData)
        .then((res) => {
          this.filePayIds.push(res.data.data[0]);
          this.form.fileIds = this.filePayIds;
          console.log("res", this.form.fileIds);
        })
        .catch((error) => {});
    },
    // 删除支付凭证
    deleteImg(file) {
      // 匹配fileList的项的fileName，相同的话把filesId对应删除
      this.uploaderList.map((item, index) => {
        if (item.name === file.file.name) {
          this.uploaderList.splice(index, 1);
          this.filePayIds.splice(index, 1);
          this.form.fileIds = this.filePayIds;
        }
      });
      console.log("index", this.uploader, this.form.fileIds);
    },

    // 获取校区列表
    fetchSchoolList() {
      getSchoolList().then((res) => {
        let list = res.data.data;
        // 遍历 list，将数据放入 schoolList
        if (res.data.data) {
          list.forEach((item) => {
            this.schoolList.push({
              value: item.id,
              text: item.name,
            });
          });
        }
      });
    },
    // 根据校区获取商品列表
    fetchGoodsList() {
      if (this.form && this.form.schoolId) {
        getGoodsList(this.form.schoolId).then((res) => {
          let list = res.data.data;
          if (res.data.data) {
            list.forEach((item) => {
              this.goodsList.push({
                value: item.id,
                text: item.name,
                price: item.price,
                carModelData: item.carModelData,
              });
            });
          }
        });
      }
    },
    // 选择身份证类型
    onDocTypeConfirm(item) {
      this.form.docType = item.value;
      this.showIdTypePicker = false;
    },
    // 选择校区
    onConfirm(item) {
      this.schoolName = item.text;
      this.form.schoolId = item.value;
      this.showPicker = false;
      if (this.form.schoolId) {
        this.fetchGoodsList();
      }
    },
    // 选择商品
    onGoodsConfirm(item) {
      this.goodsName = item.text;
      this.form.goodsId = item.value;
      // 商品金额
      this.form.goodsPrice = item.price;
      // 订单金额
      this.form.orderPrice = item.price;
      // 实付金额
      this.form.actualAmount = item.price;
      this.showGoodsPicker = false;
      console.log("this.form.goodsId", this.form.goodsId);
    },
    // // 商品改变时
    handleGoaods(value) {
      console.log("value", value);
    },
    // 车型
    onCarmodelConfirm(item) {
      this.form.carModel = item.value;
      this.carModelName = item.text;
      this.showCarmodelPicker = false;
    },

    onFailed(errorInfo) {
      this.validate = false;
      console.log('errorInfo',errorInfo);
    },
    resetValidation() {
      // 聚焦时重置有效性状态
      this.isValid = true;
    },
    onSubmit(values) {
      this.validate = true;
      createOrder(this.form).then((res) => {
        if (res.data.code === 200) {
          Toast.success(res.data.msg);
        } else {
          Toast.fail(res.data.msg);
        }
      });
    },
  },
};
</script>
<style scoped>
.no-label .van-field__label {
  display: none !important; /* 隐藏 label */
}
::v-deep .input-idCard::after {
  position: absolute;
  box-sizing: border-box;
  content: " ";
  pointer-events: none;
  right: 16px;
  bottom: 0;
  left: 16px;
  border-bottom: 1px solid #ebedf0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

::v-deep .van-cell__title.van-field__label > span {
  position: relative;
}
::v-deep .required > .van-cell__title.van-field__label > span::before {
  position: absolute;
  right: -8px;
  color: #ee0a24;
  font-size: 14px;
  content: "*";
}
.input-idCard {
  position: relative;
}
::v-deep .icon {
  color: #ee0a24;
  font-size: 14px;
}
::v-deep .upload-pay > .van-cell::after {
  border: none;
}
::v-deep .van-field--error .van-field__control, .van-field--error .van-field__control::placeholder {
    color: #eee !important;
    -webkit-text-fill-color: currentColor;
}
</style>
